/*
 * WebcamFrameGrabber.cpp
 *
 *  Created on: Sep 6, 2013
 *      Author: clivemyrie
 */

#include "WebcamFrameGrabber.h"

WebcamFrameGrabber::WebcamFrameGrabber() {
	// Structure for getting video from camera or avi
	//CvCapture* capture = 0;
	capture = 0;

	// Images to capture the frame from video or camera or from file
	frame = 0;
	frame_copy = 0;

	capture = cvCaptureFromCAM(0);
	sleep(2);

}

WebcamFrameGrabber::~WebcamFrameGrabber() {
	// TODO: Release the images, and capture memory
	cvReleaseImage(&frame_copy);
	cvReleaseCapture(&capture);
}

IplImage* WebcamFrameGrabber::grabFrame() {

	// If loaded succesfully, then:
	if (capture) {
		// Capture the frame and load it in IplImage
		if (!cvGrabFrame(capture)) {
			std::cout << "could not grab frame from capture device. exiting..."
					<< std::endl;
			return NULL;
		}
		frame = cvRetrieveFrame(capture);

		// If the frame does not exist, quit the loop
		if (!frame) {
			std::cout << "frame was NULL. exiting..." << std::endl;
			return NULL;
		}

		// Allocate framecopy as the same size of the frame
		if (!frame_copy)
			frame_copy = cvCreateImage(cvSize(frame->width, frame->height),
					IPL_DEPTH_8U, frame->nChannels);

		// Check the origin of image. If top left, copy the image frame to frame_copy.
		if (frame->origin == IPL_ORIGIN_TL)
			cvCopy(frame, frame_copy, 0);
		// Else flip and copy the image
		else
			cvFlip(frame, frame_copy, 0);

	} else { // If the capture is not loaded succesfully, then:
		std::cout << "WebcamFrameGrabber Capture device unavailable..."
				<< std::endl;
		//TODO: Do something if capture device is not available
	}
	return frame_copy;
}

